<template>
  <view>
    <up-popup
      :show="showPopup"
      :round="10"
      closeIconPos="top-right"
      closeable="true"
      @close="closePop">
      <view class="tx-map" @click="getMapLocation" v-if="position === ''">
        +选择地址
      </view>
      <view class="address" v-else>
        <text style="width: 70%">{{ position }}</text>
        <view class="update-btn" @click="getMapLocation">修改地址</view>
      </view>
      <up-form
        label-position="left"
        label-width="200rpx"
        :model="formModel"
        ref="formRef">
        <up-form-item label="门牌号" prop="houseNumber">
          <up-input
            v-model="formModel.houseNumber"
            border="none"
            placeholder="详细地址,如:1号楼101室"></up-input>
        </up-form-item>

        <up-form-item label="姓名" prop="name">
          <up-input
            v-model="formModel.name"
            border="none"
            placeholder="请填写姓名"></up-input>
        </up-form-item>

        <up-form-item label="性别" prop="sex" borderBottom>
          <up-radio-group
            v-model="formModel.sex"
            placement="row"
            @change="groupChange">
            <up-radio
              activeColor="#f9acb4"
              key="男"
              label="男"
              name="男"
              @change="radioChange"></up-radio>
            <view style="width: 50rpx"></view>
            <up-radio
              activeColor="#f9acb4"
              key="女"
              label="女"
              name="女"
              @change="radioChange"></up-radio>
          </up-radio-group>
        </up-form-item>

        <up-form-item label="电话" prop="phone">
          <up-input
            v-model="formModel.phone"
            border="none"
            placeholder="请填写手机号码"></up-input>
        </up-form-item>

        <up-form-item label="设为默认地址" prop="default">
          <up-switch v-model="switched" activeColor="#f9acb4" inactive-value="0" active-value="1"></up-switch>
        </up-form-item>
      </up-form>
      <view class="submit" @click="submitAddress">保存</view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { operateAddressService } from '../../api/address.js'
import { useUserStore } from '../../stores/user.js'
const userStore = useUserStore()

const emit = defineEmits(['success'])

// 控制弹层显示或隐藏
const showPopup = ref(false)
// 弹出层关闭
const closePop = () => {
  showPopup.value = false
  formModel.value = {
    name: '',
    phone: '',
    address: '',
    houseNumber: '',
    sex: '',
    defaults: 0,
    userId,
  }
  switched.value = 0
  position.value = ''
}
const switched = ref(0)
// 表单数据
const userId = userStore.userInfo.userId
const formModel = ref({
  name: '',
  phone: '',
  address: '',
  houseNumber: '',
  sex: '',
  defaults: 0,
  userId,
  distance: 0
})

// 选择地址
const my_latitude = ref(0)
const my_longitude = ref(0)
const position = ref('')
const getMapLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      position.value = res.name
      formModel.value.address = res.name
      my_latitude.value = res.latitude
      my_longitude.value = res.longitude
    },
    fail: () => {
      // 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判读是否有地理授权信息
      uni.getSetting({
        success: (res) => {
          const status = res.authSetting
          if (!status['scope.userLocation']) {
            // 如果授权信息中没有地理位置的授权，则需要弹窗提示用户授权地理信息
            uni.showModal({
              title: '是否授权当前位置',
              content:
                '需要获取您当前的地理位置，请确认授权，否则地图功能将无法使用',
              success: (data) => {
                // 如果用户授权了地理信息，则提示授权成功
                if (data.authSetting['scope.userLocation'] === true) {
                  uni.showToast({
                    title: '授权成功',
                    icon: 'success',
                    duration: 1000,
                  })
                  // 授权成功后，然后再次chooseLocation获取信息
                  uni.chooseLocation({
                    success: (res) => {
                      position.value = res.address
                    },
                  })
                } else {
                  uni.showToast({
                    title: '授权失败',
                    icon: 'none',
                    duration: 1000,
                  })
                }
              },
            })
          }
        },
        fail: (res) => {
          uni.showToast({
            title: '调用授权窗口失败',
            icon: 'none',
            duration: 1000,
          })
        },
      })
    },
  })
}

// 计算地址与店铺距离
// 店铺信息
const shopInfo = ref({
  latitude: 21.279015,
  longitude: 110.329155,
})
const distance = ref('')
const getDistance = () => {
  // 地球平均半径 单位公里
  const R = 6371
  const dLat = (shopInfo.value.latitude - my_latitude.value) * (Math.PI / 180)
  const dLon = (shopInfo.value.longitude - my_longitude.value) * (Math.PI / 180)
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(my_latitude.value * (Math.PI / 180)) *
      Math.cos(shopInfo.value.latitude * (Math.PI / 180)) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  distance.value = R * c
}

// 提交新增或修改地址
const submitAddress = async () => {
  getDistance()
  formModel.value.distance = (distance.value).toFixed(2)
  formModel.value.defaults = switched.value
  const res = await operateAddressService(formModel.value)
  if (res.code == '0') {
    uni.showToast({
      title: flag === '新增' ? '成功' : '成功',
      icon: 'none',
    })
    closePop()
    emit('success')
  } else {
    uni.showToast({
      title: res.message,
      icon: 'none'
    })
  }
}

// 标志是编辑或新增
const flag = ref('')
const open = (obj) => {
  showPopup.value = true
  // 编辑地址
  if (Object.keys(obj).length > 0) {
    flag.value = '编辑'
    formModel.value = obj
    position.value = obj.address
    switched.value = obj.defaults
  } else {
    flag.value = '新增'
  }
}
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.tx-map {
  width: 200rpx;
  height: 60rpx;
  border: 1rpx dashed #666;
  margin: 80rpx auto 20rpx auto;
  border-radius: 5rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #666;
}
.submit {
  width: 90%;
  height: 60rpx;
  border-radius: 20rpx;
  color: #fff;
  background-color: #7c503a;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 50rpx auto;
}
.address {
  width: 100%;
  font-size: 32rpx;
  margin-top: 80rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  .update-btn {
    font-size: 27rpx;
    width: 160rpx;
    height: 60rpx;
    border: 1px solid #666;
    margin-left: 50rpx;
    border-radius: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #888;
    float: right;
  }
}
</style>
